// components/uploadImg/uploadImg.js
import{base_url} from"../../utils/request"
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    successList:[],//上传成功后的数据地址
    i:0,
    campImgs: [], //商家信息图片
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //商家信息图片
    campUpImg() {
      let that = this;
      if (that.data.campImgs.length >= 5) {
        wx.showToast({
          title: '图片最多上传5张！',
          icon: 'none'
        });
        return;
      }
      wx.chooseMedia({
        count: 5 - (that.data.campImgs.length),
        mediaType: ['image'],
        sourceType: ['album'],
        sizeType: ['original', 'compressed'],
        success: (res) => {
          for (let item of res.tempFiles) {
            this.data.campImgs.push(item.tempFilePath)
          }
          
          this.uploadImgs();
          this.setData({
            campImgs: this.data.campImgs
          })

        }

      })
    },
    uploadImgs() {
      let that=this;
      wx.showLoading({
        title: '正在上传图片',
        mask:true
      })
      let token = wx.getStorageSync('token') ? wx.getStorageSync('token') : null
      return new Promise((resolve,reject)=>{
        wx.uploadFile({
          filePath: this.data.campImgs[that.data.i],
          name: 'file',
          header: {
            'content-type': 'application/json',
            'Authorization': `Bearer ${token}`,
          },
          url: base_url+'/common/upload',
          success: (res) => {
            this.data.successList.push(JSON.parse(res.data).fileName)
            
          },
          fail(err) {
            reject(err)
          },
          complete() {
            that.data.i++;
            if (that.data.i === that.data.campImgs.length) {
              console.log("都上传成功",that.data.successList)
              that.triggerEvent('uploadList', that.data.successList)
              wx.hideLoading()
              resolve(that.data.successList)
            } else {
              that.uploadImgs()
            }
          }
        })
      })
     
    }
  }
})